package com.fsm.common.redis.config;

import io.lettuce.core.AbstractRedisClient;
import io.lettuce.core.RedisClient;
import io.lettuce.core.TrackingArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.support.caching.CacheAccessor;
import io.lettuce.core.support.caching.CacheFrontend;
import io.lettuce.core.support.caching.ClientSideCaching;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Configuration
public class RedisConfig {

    private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        log.info(">>>>>>>>>>>>>>RedisTemplate配置开始>>>>>>>>>>>>>");
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        template.setValueSerializer(serializer);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        log.info(">>>>>>>>>>>>>>RedisTemplate配置结束>>>>>>>>>>>>>");
        return template;
    }

//    @Bean
//    public CacheFrontend<String, String> redisCacheFrontend(RedisConnectionFactory redisConnectionFactory) {
//        StatefulRedisConnection connect = getRedisConnect(redisConnectionFactory);
//        if (connect == null) {
//            return null;
//        }
//        CacheFrontend<String, String> frontend = ClientSideCaching.enable(
//                CacheAccessor.forMap(new ConcurrentHashMap<>()),
//                connect,
//                TrackingArgs.Builder.enabled());
//
//        return frontend;
//    }
//
//    private StatefulRedisConnection getRedisConnect(RedisConnectionFactory redisConnectionFactory) {
//        if(redisConnectionFactory instanceof LettuceConnectionFactory) {
//            AbstractRedisClient absClient = ((LettuceConnectionFactory) redisConnectionFactory).getNativeClient();
//            if (absClient instanceof RedisClient) {
//                return ((RedisClient) absClient).connect();
//            }
//        }
//        return null;
//    }
}

